//
//  TagPostVIewController.m
//  XPhoto
//
//  Created by sentinel on 2020/3/20.
//  Copyright © 2020 baboy. All rights reserved.
//

#import "TagPostViewController.h"
#import "UIScrollView+x.h"
#import "SysDict.h"

@interface TagPostViewController ()

@end

@implementation TagPostViewController
- (id)init{
    if (self = [self initWithNibName:NSStringFromClass([self class]) bundle:nil]){
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = self.tag;
    self.serialGroupView.title = NSLocalizedString(@"by_date", @"标签");
    [self searchWithOffset:0];
}
- (void)searchWithOffset:(NSInteger)offset{
    PostSearchArgs *args = [PostSearchArgs new];
    args.tag = self.tag;
    args.uid = @(self.post.uid);
    [Post searchByTagWithArgs:args callback:^(id  _Nonnull task, id  _Nonnull photos, NSError * _Nonnull error) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
        }
        if ([photos count] > 0) {
            if (offset == 0) {
                self.posts = [NSMutableArray array];
            }
            [self addPosts:photos];
        }
        [self.tableView stopLoading];
        self.tableView.loadMore = [photos count] == args.pageSize;
    }];
}


- (void)addPosts:(NSArray*)posts{
    NSMutableArray *grps = [Post dateSerialGroup:self.groups withPhotoRecords:posts];
    self.groups = grps;
    self.serialGroupView.items = grps;
    [self.tableView reloadData];
}

- (void)scrollViewWillBeginLoadingMore:(UIScrollView *)scrollView{
    [self searchWithOffset:self.posts.count];
}
#pragma BKTableView Delegate
- (Post *)postAtIndexPath:(NSIndexPath *)indexPath{
    Group *grp = [self.groups objectAtIndex:indexPath.section];
    Post *post = [grp.data objectAtIndex:indexPath.row];
    return post;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.groups.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    Group *grp = [self.groups objectAtIndex:section];
    NSInteger n = grp.data.count;
    return n;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    Post *post = [self postAtIndexPath:indexPath];
    
    PhotoTableViewCell *cell = [self photoTableViewCellForTableView:tableView];
    cell.post = post;
    return cell;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
